<template>
    <div class="view">
        <div ref="header" class="nav-back">
            <span class="iconfont icon-fanhui" @click="back"></span>
            <span class="nickname">&nbsp;编辑资料</span>
            <span class="save rt" @click="save">保存</span>
        </div>
        <cube-scroll class="scroll" ref="scroll" :scroll-events="['scroll']" @scroll="scrollHandler">
            <div ref="baseData" class="self-data">
                <div class="title-box">基本资料</div>
                <div class="content-box">
                    <div class="id flex"><span class="title">ID</span>
                        <span class="content ellipsis">{{user.userNo}}</span>
                    </div>
                    <div class="nickname flex" @click="showNickNameDialog">
                        <span class="title">昵称</span>
                        <span class="content ellipsis">{{user.nickname}}<i class="iconfont icon-youbian"></i></span>
                    </div>
                    <div class="sex flex"><span class="title">性别</span><span class="content ellipsis">{{user.gender==1?'男':'女'}}</span></div>
                    <div class="age flex" @click="birthdayPicker"><span class="title">生日</span>
                        <span class="content ellipsis" v-if="user.birthday">{{user.birthday | timeStampToDay}}</span>
                        <span class="content ellipsis none-content" v-else>未填写<i class="iconfont icon-youbian"></i></span>
                    </div>
                    <div class="home flex"
                         @click="showAddressPicker('选择居住地',['provinceId','cityId','districtId'],['snapProvinceId','snapCityId','snapDistrictId'], self.snapProvinceId)">
                        <span>居住地</span>
                        <span class="ellipsis">{{self.snapCityId}}<i class="iconfont icon-youbian"></i></span>
                    </div>
                    <div class="industry flex" @click="showIndustryPicker('industry')">
                        <span class="title">行业</span>
                        <span class="content ellipsis" v-if="user.industry!==0">{{industry}}<i class="iconfont icon-youbian"></i></span>
                        <span class="content ellipsis none-content" v-else>未填写<i class="iconfont icon-youbian"></i></span>
                    </div>
                    <div class="company-position flex" @click="showCompanyPositionDialog"><span class="title">公司职位</span>
                        <span class="ellipsis" v-if="user.companyPosition!==''">{{user.companyPosition}}<i class="iconfont icon-youbian"></i></span>
                        <span class="ellipsis none-content" v-else>未填写<i class="iconfont icon-youbian"></i></span>
                    </div>
                    <div class="identity-introduction">
                        <div class="title">自我介绍</div>
                        <cube-textarea v-model="identityIntroduction" placeholder="可在此处添加您成功配对的案例及数量!" @input="identityIntroductionInput"></cube-textarea>
                    </div>

                </div>
            </div>
        </cube-scroll>
    </div>
</template>

<script lang="ts">
    import {Component, Vue} from "vue-property-decorator";
    import Scene from "@/render/Scene";
    import Http from "@/service/Http";

    import {Getter, Action, State, Mutation} from "vuex-class";
    import {InterfaceUser} from "@/interface/InterfaceUser";
    import {updateUser} from "@/store/dispatches";
    import UserEntity from "@/entity/UserEntity";
    import CommonUnit from "@/unit/CommonUnit";
    import DialogConfig from "@/constant/DialogConfig";

    @Component({
        components: {}
    })
    export default class MatchmakerDataEdit extends Scene {

        @State("UserStore")
        public user!: InterfaceUser;
        private scrollType: string = "";
        private dataPicker: any = "";
        private industryPicker: any = "";
        private industry: string = "";
        private industryData: any[] = [];
        private identityIntroduction: string = "";
        private originalBirthday: number = 0;
        private currentKey: string = "";
        private currentSnap: string = "";
        private currentChilrenKey: string = "";
        private currentKeyArray: string[] = [];
        private currentSnapArray: string[] = [];
        private addressJson: any[] = [];
        private addressPicker: any = "";

        @State("DeviceStore")
        private device: any;

        private get self(): InterfaceUser {
            return this.user;
        }

        private set self(user: InterfaceUser) {
            updateUser(user);
        }

        private showNickNameDialog() {
            (<any> this).$createDialog({
                type: "prompt",
                title: "修改昵称",
                content: "昵称长度为2～20个字。<br/>禁止包含黄色、暴力及广告内容!",
                prompt: {
                    value: this.user.nickname,
                    placeholder: this.user.nickname,
                    maxlength: 20,
                    clearable: {
                        visible: true,
                        blurHidden: true
                    }
                },
                onConfirm: (e: any, promptValue: string) => {
                    if (promptValue.length < 2 || promptValue.length > 20 || typeof (promptValue) !== "string") {
                        (<any> this).$createToast({
                            time: 2000,
                            txt: "昵称长度为2～20个字。请检查后重新修改",
                            type: "warn"
                        }).show();
                    } else {
                        this.$set(this.self, "nickname", promptValue);
                    }
                }
            }).show();
        }

        private showCompanyPositionDialog() {
            (<any> this).$createDialog({
                type: "prompt",
                title: "公司职位",
                content: "长度为2～20个字。<br/>禁止包含黄色、暴力及广告内容!",
                prompt: {
                    value: this.user.companyPosition,
                    placeholder: this.user.companyPosition,
                    maxlength: 20,
                    clearable: {
                        visible: true,
                        blurHidden: true
                    }
                },
                onConfirm: (e: any, promptValue: string) => {
                    if (promptValue.length < 2 || promptValue.length > 20 || typeof (promptValue) !== "string") {
                        (<any> this).$createToast({
                            time: 2000,
                            txt: "长度为2～20个字。请检查后重新修改",
                            type: "warn"
                        }).show();
                    } else {
                        this.$set(this.self, "companyPosition", promptValue);
                    }
                }
            }).show();
        }

        private identityIntroductionInput(): void {
            this.$set(this.user, "identityIntroduction", this.identityIntroduction);
        }

        private birthdayPicker(): void {//出生日期选择
            if (this.originalBirthday === 0) {
                if (!this.dataPicker) {
                    this.dataPicker = (<any> this).$createDatePicker({
                        title: "选择出生日期",
                        subtitle: "仅可修改一次",
                        min: new Date(new Date().getFullYear() - 100, new Date().getMonth(), 1),
                        max: new Date(new Date().getFullYear() - 18, new Date().getMonth(), 1),
                        value: this.user.birthday ? new Date(this.user.birthday * 1000) : new Date(new Date().getFullYear() - 25, new Date().getMonth(), 1),
                        onSelect: this.selectBirthday
                    });
                }
                this.dataPicker.show();
            }
        }

        private showIndustryPicker(key: string): void {
            if (!this.industryPicker) {
                this.industryPicker = (<any> this).$createPicker({
                    title: "选择行业",
                    selectedIndex: (this as any).user[key] !== 0 ? [(this as any).user[key] - 1] : [0],
                    data: [this.industryData],
                    onSelect: this.selectIndustry
                });
            }
            this.industryPicker.show();
        }

        private selectIndustry(selectedVal: any, selectedIndex: any, selectedText: any) {
            this.industry = selectedText.join(",");
            this.$set(this.self, "industry", selectedVal.join(","));
            this.$set(this.self, "snapIndustry", selectedText.join(","));
        }

        private selectBirthday(value: string) {
            const birthday = Date.parse(value);
            this.$set(this.self, "birthday", birthday / 1000);
        }

        private scrollHandler(pos: any): void {//scroll滚动事件
            //this.pullDownY = pos.y;
        }

        private addressSelect(value: any[], index: number[], text: string[]) {
            this.$set(this.self, this.currentKeyArray[0], value[0]);
            this.$set(this.self, this.currentKeyArray[1], value[1]);
            this.$set(this.self, this.currentSnapArray[0], index.join(","));
            this.$set(this.self, this.currentSnapArray[1], text.join(" "));
            if (this.currentKeyArray.length === 3) {
                this.$set(this.self, this.currentKeyArray[2], value[2]);
            }
        }

        private async showAddressPicker(title: string, key: string[], snap: string[], defaultIndex: string = "", childrenKey: string = ""): Promise<any> {
            this.currentKeyArray = key;
            this.currentSnapArray = snap;
            this.currentChilrenKey = childrenKey;

            const toast = (<any> this).$createToast({
                time: 0,
                txt: "载入地区数据",
                mask: true
            }).show();
            let result: any[] = await Http.read(this.api.addressJson);
            if (key.length !== 3) {
                for (let i in result) {
                    for (let j in result[i].children) {
                        delete result[i].children[j].children;
                    }
                }
            }
            this.addressJson.push(...result);
            toast.hide();
            this.addressPicker = (<any> this).$createCascadePicker({
                title: title,
                data: result,
                selectedIndex: defaultIndex.split(","),
                onSelect: this.addressSelect,
            });
            this.addressPicker.show();
        }

        private back(): void {
            if (Number(this.$route.query.isNew) === 1) {
                const dialogConfig = new DialogConfig();
                (<any> this).$createDialog({
                    ...dialogConfig.getAppDownloadTipConfig(),
                    onConfirm: () => {
                        this.redirectTo({
                            name: "appDownload"
                        });
                    },
                    onCancel: () => {
                        this.navigateBack();
                    }
                }).show();
            }else{
                this.navigateBack();
            }
        }

        private async save(): Promise<any> {
            const userEntity = new UserEntity(this.user);
            let toast = (<any> this).$createToast({
                time: 0,
                txt: "保存中...",
                mask: true
            }).show();
            const baseInfoParameter = userEntity.getMatchmakerBaseInfo;

            if (this.originalBirthday > 0) {
                delete baseInfoParameter.birthday;
            }

            try {
                const baseInfoResult = await Http.post(this.api.saveMatchmakerInfo, {...baseInfoParameter}, {token: this.user.token});
                if (baseInfoResult.code === 1) {
                    this.authentication();
                    toast = (<any> this).$createToast({
                        time: 2500,
                        txt: "保存成功，正在更新资料",
                        type: "correct",
                        mask: true,
                        onTimeout: () => {
                            if (Number(this.$route.query.isNew) === 1) {
                                const dialogConfig = new DialogConfig();
                                (<any> this).$createDialog({
                                    ...dialogConfig.getAppDownloadTipConfig(),
                                    onConfirm: () => {
                                        this.redirectTo({
                                            name: "appDownload"
                                        });
                                    },
                                    onCancel: () => {
                                        this.navigateBack();
                                    }
                                }).show();
                            }else{
                                this.navigateBack();
                            }
                        }
                    }).show();
                } else {
                    toast.hide();
                    this.globalSingleResultToast(baseInfoResult);
                }
            } catch (e) {
                toast.hide();
            }
        }

        private mounted(): void {
            this.identityIntroduction = this.user.identityIntroduction;
            this.originalBirthday = this.user.birthday;
            this.industryData = [
                {text: "农、林、牧、渔业", value: 1},
                {text: "采矿业", value: 2},
                {text: "制造业", value: 3},
                {text: "电力、燃气及水的生产和供应", value: 4},
                {text: "建筑业", value: 5},
                {text: "交通运输、仓储和邮政", value: 6},
                {text: "信息传输、计算机服务和软件业", value: 7},
                {text: "批发和零售", value: 8},
                {text: "住宿和餐饮业", value: 9},
                {text: "金融业", value: 10},
                {text: "房地产业", value: 11},
                {text: "租赁和商务服务", value: 12},
                {text: "科学研究、技术服务和地质勘查", value: 13},
                {text: "科学研水利、环境和公共设施管理", value: 14},
                {text: "居民服务和其他服务", value: 15},
                {text: "教育", value: 16},
                {text: "卫生、社会保障和社会福利", value: 17},
                {text: "文化、体育和娱乐业", value: 18},
                {text: "公共管理和社会组织", value: 19},
                {text: "国际组织", value: 20},
                {text: "其它", value: 21}
            ];
            if (Number(this.user.industry) !== 0) {
                const index = this.industryData.findIndex((value) => value.value == this.user.industry);
                this.industry = this.industryData[index].text;
            }
            this.$nextTick(() => {
                let type = String(this.$route.query.type);
                if (type !== "undefined") {
                    let scrollY = (this as any).$refs[type].offsetTop;
                    (this as any).$refs.scroll.scrollTo(0, -scrollY, 0);
                }
            });
        }
    }
</script>

<style scoped lang="stylus">
    .view
        width 100vw;
        height 100vh;
        background $theme-page-common-background-color;

        .nav-back
            width 100vw;
            position fixed;
            top var(--safe-area-inset-top);
            left 0px;
            z-index: 100;
            color $theme-common-color;
            padding 15px 10px;
            background rgba(255, 255, 255, 1);
            border-bottom 1px solid $theme-line-color;

            .save
                font-size 16px;

            .nickname
                font-size 16px;
                color $theme-common-color;

        .scroll
            margin-top 47px;
            position relative;
            height calc(100vh - var(--safe-area-inset-top) - var(--safe-area-inset-bottom));

        > div
            .title-box
                padding 15px;

            .content-box
                background-color #fff;

                > div
                    padding 15px;
                    border-bottom 1px solid $theme-line-color;
                    justify-content: space-between;

                    .title
                        display inline-block;
                        width 60px;

                    .content
                        display inline-block;
                        width calc(100vw - 30px - 80px);
                        text-align right;

                    .none-content
                        color $theme-common-color;

                    i.icon-youbian
                        color $theme-viceColor-font;
                        padding-left 6px;

                .identity-introduction
                    margin-bottom 70px;

                    .title
                        margin-bottom 10px;

                    >>> .cube-textarea-wrapper
                        height 80px;
                        border 1px solid $theme-line-color;
                        border-radius 8px;
                        overflow hidden;

                        &::after
                            border none;

</style>
